//
//  RoundedSearchBar.m
//  XMJJ_zml
//
//  Created by 杨何华 on 2025/5/9.
//

#import "RoundedSearchBar.h"

@implementation RoundedSearchBar
 
 
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}
-(void)setSearchText:(NSString *)searchText
{
    _searchText = searchText;
    self.textField.placeholder = self.searchText.length >0 ? self.searchText: @"请输入内容";

}
- (void)commonInit {
    // 设置默认属性
//    self.backgroundColor = [UIColor whiteColor];
    self.backgroundColor = kColorHEX(0xF8F9FA);

    self.layer.cornerRadius = 15.0;
    self.layer.masksToBounds = YES;
    
    
    // 创建搜索按钮
    UIImage * searchImage = [UIImage imageNamed:@"search"];
    self.searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.searchButton.frame = CGRectMake(10, self.bounds.size.height/2-7, searchImage.size.width, searchImage.size.height);
    [self.searchButton setBackgroundImage:searchImage forState:UIControlStateNormal];
    [self.searchButton addTarget:self action:@selector(searchButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.searchButton];
    
    // 创建文本输入框
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(30, 0, self.bounds.size.width - 50, self.bounds.size.height)];
    
//    self.textField.placeholder = self.searchText.length >0 ? self.searchText: @"请输入内容";
    
    // 设置placeholder颜色
 
    // 设置placeholder的颜色和字体
    UIColor *placeholderColor = kColorHEX(0xCBC3D2); // 自定义颜色
    UIFont *placeholderFont = [UIFont systemFontOfSize:13.0]; // 自定义字体

    NSDictionary *attributes = @{
        NSForegroundColorAttributeName: placeholderColor,
        NSFontAttributeName: placeholderFont
    };
     self.textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入内容" attributes:attributes];

    

    self.textField.delegate = self;
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.textField.returnKeyType = UIReturnKeySearch;
    [self addSubview:self.textField];
    
}

- (void)setCornerRadius:(CGFloat)radius {
    self.layer.cornerRadius = radius;
}

- (void)setBorderColor:(UIColor *)color width:(CGFloat)width {
    self.layer.borderColor = color.CGColor;
    self.layer.borderWidth = width;
}

- (void)searchButtonTapped {
    if (self.searchAction) {
        self.searchAction(self.textField.text);
    }
}

#pragma mark - UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
//    [textField resignFirstResponder];
    if (self.searchAction) {
        self.searchAction(textField.text);
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (self.searchAction) {
        self.searchAction(textField.text);
    }
    return YES;
}



@end
